package servlet;

import dao.PaymentRecordDao;
import dao.AccountBalanceDao;
import entity.Owner;
import entity.PaymentRecord;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import util.DBUtil;

@WebServlet("/payment")
public class PaymentServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Connection conn = null;
        try {
            // 获取当前登录用户
            Owner owner = (Owner) request.getSession().getAttribute("owner");
            if (owner == null) {
                response.sendRedirect("login.jsp");
                return;
            }

            // 获取表单数据
            int feeTypeId = Integer.parseInt(request.getParameter("feeTypeId"));
            BigDecimal quantity = new BigDecimal(request.getParameter("quantity"));
            BigDecimal amount = new BigDecimal(request.getParameter("amount"));

            // 开启事务
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false);

            // 创建支付记录
            PaymentRecord record = new PaymentRecord();
            record.setOwnerId(owner.getId());
            record.setFeeTypeId(feeTypeId);
            record.setQuantity(quantity);
            record.setAmount(amount);

            // 保存支付记录
            PaymentRecordDao recordDao = new PaymentRecordDao();
            recordDao.addPaymentRecord(record, conn);

            // 更新账户余额
            AccountBalanceDao balanceDao = new AccountBalanceDao();
            balanceDao.updateBalance(owner.getId(), feeTypeId, amount, conn);

            // 提交事务
            conn.commit();

            // 重定向到支付记录页面
            response.sendRedirect("paymentHistory.jsp");

        } catch (Exception e) {
            // 发生异常时回滚事务
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            request.setAttribute("error", "支付失败：" + e.getMessage());
            request.getRequestDispatcher("payment.jsp").forward(request, response);
        } finally {
            // 关闭连接
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}